from operator import itemgetter, attrgetter

class NoJobsError(Exception):
    pass

class RunQueue(object):
    
    def __init__(self):
        self.length = 0
        self.jobs = []

    def add_job(self, job):
        self.jobs.append(job)
        self.length +=1

        return job

    def provide_job(self):
        try:
            job = self.jobs.pop()
        except IndexError:
            raise NoJobsError
        else:
            self.length -=1
            return job

    def optimize(self):
        self.jobs = sorted(self.jobs, key=attrgetter('host'))
